import { Body, Controller, Get, Post, Req } from '@nestjs/common';
import { TokenService } from './token.service';
import { Request } from 'express';
import { TokenInfoDto } from './dto/token-info.dto';

@Controller('token')
export class TokenController {
  constructor(private readonly tokenService: TokenService) {}

  /**
   * 验证当前请求中的token
   */
  @Get('verify')
  verifyCurrentToken(@Req() req: Request): TokenInfoDto {
    const token = this.tokenService.extractTokenFromHeader(req);
    
    if (!token) {
      return {
        valid: false,
        message: 'No token provided'
      };
    }
    
    const decoded = this.tokenService.verifyToken(token);
    
    if (!decoded) {
      return {
        valid: false,
        message: 'Invalid token'
      };
    }
    
    // 获取角色信息，支持多种字段名
    const roles = decoded.roles || decoded.roleCodes || [];
    
    return {
      valid: true,
      userId: decoded.sub || decoded.userId || decoded.id,
      username: decoded.username || decoded.name || decoded.email,
      roles: roles,
      permissions: decoded.permissions || [],
      expiresAt: decoded.exp,
      issuer: decoded.iss
    };
  }

  /**
   * 验证指定的token
   */
  @Post('verify')
  verifyToken(@Body() body: { token: string }): TokenInfoDto {
    if (!body.token) {
      return {
        valid: false,
        message: 'No token provided'
      };
    }
    
    const decoded = this.tokenService.verifyToken(body.token);
    
    if (!decoded) {
      return {
        valid: false,
        message: 'Invalid token'
      };
    }
    
    // 获取角色信息，支持多种字段名
    const roles = decoded.roles || decoded.roleCodes || [];
    
    return {
      valid: true,
      userId: decoded.sub || decoded.userId || decoded.id,
      username: decoded.username || decoded.name || decoded.email,
      roles: roles,
      permissions: decoded.permissions || [],
      expiresAt: decoded.exp,
      issuer: decoded.iss
    };
  }

  /**
   * 获取当前用户角色
   */
  @Get('roles')
  getUserRoles(@Req() req: Request) {
    const token = this.tokenService.extractTokenFromHeader(req);
    
    if (!token) {
      return {
        success: false,
        message: 'No token provided'
      };
    }
    
    const roles = this.tokenService.getUserRoles(token);
    
    return {
      success: true,
      roles
    };
  }

  /**
   * 检查当前用户是否具有指定角色
   */
  @Post('check-role')
  checkUserRole(@Body() body: { role: string }, @Req() req: Request) {
    const token = this.tokenService.extractTokenFromHeader(req);
    
    if (!token) {
      return {
        success: false,
        message: 'No token provided'
      };
    }
    
    if (!body.role) {
      return {
        success: false,
        message: 'No role specified'
      };
    }
    
    const hasRole = this.tokenService.checkRoles(token, [body.role]);
    
    return {
      success: true,
      hasRole
    };
  }
} 